﻿using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using System.Collections.Generic;
using Infragistics.WebUI.UltraWebGrid;
using uMES.LeanManufacturing.Common;
using System.IO;
using uMES.LeanManufacturing.ReportBusiness;
using uMES.LeanManufacturing.ParameterDTO;
using System.Text;
using System.Text.RegularExpressions;
using uMES.LeanManufacturing.DBUtility;
using System.Drawing;
using System.Data.OracleClient;

public partial class uMESSpecFinishConfirmPopupForm : System.Web.UI.Page
{
    uMESCommonBusiness common = new uMESCommonBusiness();
    uMESSecondaryWarehouseBusiness bll = new uMESSecondaryWarehouseBusiness();
    uMESContainerCheckBusiness containerCheckBal = new uMESContainerCheckBusiness();
    string businessName = "检验管理", parentName = "containerspecfinishinfo";

    public FreeTextBoxControls.FreeTextBox oHtml;
    protected void Page_Load(object sender, EventArgs e)
    {

        if (!IsPostBack)
        {
            if (Session["PopupData"] !=null)
            {
                Dictionary<string, string> para = (Dictionary<string, string>)Session["PopupData"];
                ///界面控件赋值
                BindDataToControls(para);
                GetSpecDispatchInfo(para);
                GetSpecReportInfo(para);
                GetSpecCheckInfo(para);
                GetQualityRecordInfo(para);
                GetSpecUnqualifiedProductsInfo(para);
                GetScrapInfo(para);
            }
        }


    }

    /// <summary>
    /// 界面控件赋值
    /// </summary>
    protected void BindDataToControls(Dictionary<string, string> para)
    {
        try
        {
            //工作令号
            if (para.ContainsKey("ProcessNo"))
            {
                txtDispProcessNo.Text =para["ProcessNo"];
            }

            //作业令号
            if (para.ContainsKey("OprNo"))
            {
                txtDispOprNo.Text = para["OprNo"];
            }

            //批次号
            if (para.ContainsKey("ContainerName"))
            {
                txtDispContainerName.Text = para["ContainerName"];
            }

            //图号
            if (para.ContainsKey("ProductName"))
            {
                txtDispProductName.Text  = para["ProductName"];
            }

            //名称
            if (para.ContainsKey("Description"))
            {
                txtDispDescription.Text = para["Description"];
            }

            //批次数量
            if (para.ContainsKey("ConQty"))
            {
                txtConQty.Text  = para["ConQty"];
            }

            //计划开始时间
            if (para.ContainsKey("StartTime"))
            {
                txtStartTime.Text  = para["StartTime"];
            }

            //计划结束时间
            if (para.ContainsKey("EndTime"))
            {
                txtEndTime.Text = para["EndTime"];
            }


            //跟踪卡ID
            if (para.ContainsKey("ContainerID"))
            {
                txtContainerID.Text = para["ContainerID"];
            }

            //工艺规程ID
            if (para.ContainsKey("WorkflowID"))
            {
                txtWorkflowID.Text = para["WorkflowID"];
            }


            //工序ID
            if (para.ContainsKey("SpecID"))
            {
                txtSpecID.Text = para["SpecID"];
            }

            //计量单位ID
            if (para.ContainsKey("UomID"))
            {
                txtUomID.Text = para["UomID"];
            }

            //工序名称
            if (para.ContainsKey("SpecName"))
            {
                txtSpecName.Text = para["SpecName"];
            }

            //生产订单
            if (para.ContainsKey("MfgOrderName"))
            {
                txtMfgOrderName.Text = para["MfgOrderName"];
            }

            //分厂ID
            if (para.ContainsKey("FactoryID"))
            {
                txtFactoryID.Text = para["FactoryID"];
            }
        }
        catch (Exception Ex)
        {

            ShowStatusMessage(Ex.Message, false);
        }
    }

    /// <summary>
    /// 获取工序派工信息
    /// </summary>
    /// <param name="para"></param>
    protected void GetSpecDispatchInfo(Dictionary<string,string> para)
    {
        try
        {
            int intDispatchQty;
            txtDispatchQty.Text = "0";
            DataTable dt = bll.GetSpecDispatchInfo(para,out intDispatchQty);
            txtDispatchQty.Text = intDispatchQty.ToString();
            wgDispatch.DataSource = dt;
            wgDispatch.DataBind();
        }
        catch(Exception Ex)
        {
            ShowStatusMessage(Ex.Message, false);
        }

    }

    /// <summary>
    /// 获取工序报工信息
    /// </summary>
    /// <param name="para"></param>
    protected void GetSpecReportInfo(Dictionary<string, string> para)
    {
        try
        {
            para.Add("ReportType", "'0','3'");
            int intReportQty = 0;
            txtReportQty.Text = "0";
            DataTable dt = bll.GetSpecReportInfo(para,out intReportQty);
            txtReportQty.Text = intReportQty.ToString();
            wgReport.DataSource = dt;
            wgReport.DataBind();
        }
        catch (Exception Ex)
        {
            ShowStatusMessage(Ex.Message, false);
        }

    }

    /// <summary>
    /// 获取检验信息
    /// </summary>
    /// <param name="para"></param>
    protected void GetSpecCheckInfo(Dictionary<string, string> para)
    {
        try
        {
       
            DataTable dt = bll.GetSpecCheckInfo(para);
            wgCheck.DataSource = dt;
            wgCheck.DataBind();
        }
        catch (Exception Ex)
        {
            ShowStatusMessage(Ex.Message, false);
        }

    }

    /// <summary>
    /// 获取质量记录信息
    /// </summary>
    /// <param name="para"></param>
    protected void GetQualityRecordInfo(Dictionary<string, string> para)
    {
        try
        {
            DataTable dt = bll.GetSavedQualInfo(para);
            wgQual.DataSource = dt;
            wgQual.DataBind(); 
        }
        catch (Exception Ex)
        {
            ShowStatusMessage(Ex.Message, false);
        }

    }

    /// <summary>
    /// 获取不合格品审理信息
    /// </summary>
    /// <param name="para"></param>
    protected void GetSpecUnqualifiedProductsInfo(Dictionary<string, string> para)
    {
        try
        {
            DataTable dt = bll.GetRejectAppInfo(para);
            wgUnQualified.DataSource = dt;
            wgUnQualified.DataBind();
        }
        catch (Exception Ex)
        {
            ShowStatusMessage(Ex.Message, false);
        }

    }

    /// <summary>
    /// 获取报废信息
    /// </summary>
    /// <param name="para"></param>
    protected void GetScrapInfo(Dictionary<string, string> para)
    {
        try
        {
            DataTable dt = bll.GetSpecScrapInfo(para);
            wgScrapInfo.DataSource = dt;
            wgScrapInfo.DataBind();
        }
        catch (Exception Ex)
        {
            ShowStatusMessage(Ex.Message, false);
        }

    }


    /// <summary>
    /// 提示信息
    /// </summary>
    /// <param name="strMessage"></param>
    /// <param name="boolResult"></param>
    protected void ShowStatusMessage(string strMessage, Boolean boolResult)
    {
        lStatusMessage.Text = strMessage;

        if (boolResult == true)
        {
            lStatusMessage.ForeColor = Color.Black;
        }
        else
        {
            lStatusMessage.ForeColor = Color.Red;
        }
    }

    /// <summary>
    /// 验证是否是正整数
    /// </summary>
    /// <param name="inString"></param>
    /// <returns></returns>
    public static bool IsInt(string inString)
    {
        Regex regex = new Regex("^[0-9]*[1-9][0-9]*$");
        return regex.IsMatch(inString.Trim());
    }

    /// <summary>
    /// 确认按钮事件
    /// </summary>
    /// <param name="sender"></param>
    /// <param name="e"></param>
    protected void btnConfirm_Click(object sender, EventArgs e)
    {
        try
        {
            Dictionary<string, string> userInfo = Session["UserInfo"] as Dictionary<string, string>;
            string strMessage="";

            Dictionary<string, string> para1 = new Dictionary<string, string>();
            para1.Add("ContainerID", txtContainerID.Text);
            para1.Add("SpecName",txtSpecName.Text);
           // para1.Add("WorkflowID", txtWorkflowID.Text);
            DataTable dtSave = bll.GetContainerSpecFinishInfo(para1);
            if (dtSave.Rows.Count>0)
            {
                //MoveContainer(new Dictionary<string, string>() { { "ContainerName", txtDispContainerName.Text },
                //    { "ApiUserName", userInfo["ApiEmployeeName"] }, { "ApiPassword", userInfo["ApiPassword"]}
                //}, ref strMessage);

                ShowStatusMessage("该工序已进行完工确认", false);

                return;
            }

            if (txtDispatchQty.Text != txtReportQty.Text)
            {
                ShowStatusMessage("派工数不等于报工数，无法进行完工确认！", false);
                return;
            }
            //判断是否有未走完的质量记录,有的情况下判断是否有不合格审理。若没有则算没走完，若有则判断是否填入那三个数
            ResultModel re = containerCheckBal.IsCompleteQuality(txtContainerID.Text, txtWorkflowID.Text, txtSpecID.Text);
            if (re.IsSuccess == false) {
                ShowStatusMessage(re.Message,false);return;
            }

            //判断该工序是否已完成检验
            para1.Add("ScanContainerName", txtDispContainerName.Text);
            para1.Add("CurrentPageIndex", "1");
            para1.Add("PageSize", "100");
            uMESPagingDataDTO CheckResult = containerCheckBal.GetCheckData(para1);
            if (CheckResult.DBTable.Rows.Count > 0)
            {
                DataRow[] dr = CheckResult.DBTable.Select("ischecked <> 1 OR ischecked IS NULL");
                if (dr.Length > 0)
                {
                    ShowStatusMessage("该工序有尚未完成的检验记录，无法进行完工确认！", false);
                    return;
                }
            }

            //以字典形式传递参数
            Dictionary<string, object> para = new Dictionary<string, object>();
            DataSet ds = new DataSet();

            DataTable dtMain = new DataTable();
            dtMain.Columns.Add("ID");//唯一标识
            dtMain.Columns.Add("ContainerID");//生产批次ID
            dtMain.Columns.Add("ProcessNo");//工作令号
            dtMain.Columns.Add("OprNo");//作业令号
            dtMain.Columns.Add("MfgOrderName");//生产订单号
            dtMain.Columns.Add("ConQty");//批次数量
            dtMain.Columns.Add("Qty");//完工数量
            dtMain.Columns.Add("EligibilityQty");//合格数量
            dtMain.Columns.Add("RBQty");//让步使用数
            dtMain.Columns.Add("FixQty");//返工返修数量
            dtMain.Columns.Add("ScrapQty");//报废数量
            dtMain.Columns.Add("FactoryID");//分厂ID
            dtMain.Columns.Add("confirmDate");//确认日期
            dtMain.Columns.Add("confirmemployeeID");//确认人
            dtMain.Columns.Add("Notes");//备注
            dtMain.Columns.Add("ProductName");//产品/图号
            dtMain.Columns.Add("Description");//名称
            dtMain.Columns.Add("ContainerName");//生产批次号
            dtMain.Columns.Add("UOMID");//计量单位ID
            dtMain.Columns.Add("SpecID");//工序ID
            dtMain.Columns.Add("WorkflowID");//工艺规程ID
            //合格数
            int  intEligibilityQty = 0;
            //报废数
            int intScrapQty = 0;

            for (int i=0;i<wgCheck.Rows.Count;i++)
            {
                //if (!string.IsNullOrEmpty(wgCheck.Rows[i].Cells.FromKey("checktype").Text))
                //{
                //    if (wgCheck.Rows[i].Cells.FromKey("checktype").Text== "工序终检" || wgCheck.Rows[i].Cells.FromKey("checktype").Text=="")
                //    {
                        //if (!string.IsNullOrEmpty(wgCheck.Rows[i].Cells.FromKey("ScrapQty").Text))
                        //{
                        //    strScrapQty = wgCheck.Rows[i].Cells.FromKey("ScrapQty").Text;
                        //}
                        if (!string.IsNullOrEmpty(wgCheck.Rows[i].Cells.FromKey("EligibilityQty").Text))
                        {
                            intEligibilityQty += int.Parse(wgCheck.Rows[i].Cells.FromKey("EligibilityQty").Text);
                        }
                //    }
                //}
            }

            //让步使用
            int intRBQty = 0;

            //返工返修数
            int intFixQty = 0;

            //获取不合格品审理结果
            DataTable dtReject = bll.GetRejectAppResultInfo(para1);
            if (dtReject.Rows.Count>0)
            {
                for (int i=0;i<dtReject.Rows.Count;i++)
                {
                    if (!string.IsNullOrEmpty(dtReject.Rows[i]["disposeresult"].ToString()))
                    {
                        if (dtReject.Rows[i]["disposeresult"].ToString()== "10")
                        {
                            if (!string.IsNullOrEmpty(dtReject.Rows[i]["disqty"].ToString()))
                            {
                                intRBQty += int.Parse(dtReject.Rows[i]["disqty"].ToString());
                            }
                        }

                        if (dtReject.Rows[i]["disposeresult"].ToString() == "20")
                        {
                            if (!string.IsNullOrEmpty(dtReject.Rows[i]["disqty"].ToString()))
                            {
                                intFixQty += int.Parse(dtReject.Rows[i]["disqty"].ToString());
                            }
                        }

                        if (dtReject.Rows[i]["disposeresult"].ToString() == "30")
                        {
                            if (!string.IsNullOrEmpty(dtReject.Rows[i]["disqty"].ToString()))
                            {
                                intScrapQty += int.Parse(dtReject.Rows[i]["disqty"].ToString());
                            }
                        }
                    }

                }
            }
              dtMain.Rows.Add();
            int intMainRow = dtMain.Rows.Count - 1;
            string strID = Guid.NewGuid().ToString();
            dtMain.Rows[intMainRow]["ID"]= strID + "㊣String";
            dtMain.Rows[intMainRow]["ContainerID"]=txtContainerID.Text + "㊣String";
            dtMain.Rows[intMainRow]["ProcessNo"]=txtDispProcessNo.Text + "㊣String";
            dtMain.Rows[intMainRow]["OprNo"]=txtDispOprNo.Text + "㊣String";
            dtMain.Rows[intMainRow]["MfgOrderName"] = txtMfgOrderName.Text + "㊣String";
            dtMain.Rows[intMainRow]["ConQty"] = txtConQty.Text + "㊣Integer";
            dtMain.Rows[intMainRow]["Qty"] = txtReportQty.Text + "㊣Integer";
            dtMain.Rows[intMainRow]["EligibilityQty"] = intEligibilityQty.ToString() + "㊣Integer";
            dtMain.Rows[intMainRow]["ScrapQty"] = intScrapQty.ToString() + "㊣Integer";
            dtMain.Rows[intMainRow]["RBQty"] = intRBQty.ToString() + "㊣Integer";
            dtMain.Rows[intMainRow]["FixQty"] = intFixQty.ToString() + "㊣Integer";
            dtMain.Rows[intMainRow]["FactoryID"] = txtFactoryID.Text + "㊣String";
            dtMain.Rows[intMainRow]["confirmDate"] = System.DateTime.Now + "㊣Date";
            dtMain.Rows[intMainRow]["confirmemployeeID"] = userInfo["EmployeeID"] + "㊣String";
            dtMain.Rows[intMainRow]["Notes"] = "" + "㊣String";
            dtMain.Rows[intMainRow]["ProductName"] = txtDispProductName.Text + "㊣String";
            dtMain.Rows[intMainRow]["Description"] = txtDispDescription.Text + "㊣String";
            dtMain.Rows[intMainRow]["ContainerName"] = txtDispContainerName.Text + "㊣String";
            dtMain.Rows[intMainRow]["UOMID"] = txtUomID.Text + "㊣String";
            dtMain.Rows[intMainRow]["SpecID"] = txtSpecID.Text + "㊣String";
            dtMain.Rows[intMainRow]["WorkflowID"] = txtWorkflowID.Text + "㊣String";

            dtMain.Rows.Add();
            dtMain.Rows[dtMain.Rows.Count - 1]["ID"] = "" + "㊣String";
            ds.Tables.Add(dtMain);
            ds.Tables[ds.Tables.Count - 1].TableName = "ContainerSpecFinishInfo" + "㊣ID";

            //保存数据
            para.Add("dsData", ds);
            bool result = bll.SaveDataToDatabaseNew(para, out strMessage);
            if (result == true)
            {
                Dictionary<string, string> paraNew = new Dictionary<string, string>();
                paraNew.Add("WorkflowID", txtWorkflowID.Text);
                //判断工序是否是最后一道序
                bool isLastSpec = false;
                DataTable dtSpec = bll.GetSpecInfo(paraNew);
                DataRow[] dr = dtSpec.Select("specid='"+txtSpecID.Text+"'");
                if (dr.Length>0)
                {
                    if (!string.IsNullOrEmpty(dr[0]["sequence"].ToString()))
                    {
                        if (dtSpec.Rows.Count == Convert.ToUInt32(dr[0]["sequence"].ToString()))
                        {
                            isLastSpec = true;
                        }
                    }
                }
                if (isLastSpec==true)
                {
                    int intResult = bll.UpdateFinishState(txtContainerID.Text);
                }
                else
                    {
                    paraNew.Add("ContainerName", txtDispContainerName.Text);
                    paraNew.Add("ApiUserName", userInfo["ApiEmployeeName"]);
                    paraNew.Add("ApiPassword", userInfo["ApiPassword"]);

                    result = MoveContainer(paraNew,ref strMessage); ;//bll.RunMoveStd(paraNew, ref strMessage);
                }
           
            }
            if (result == true)
            {
                strMessage = "完工确认成功！";
                //关闭窗口并刷新
                Response.Write("<script>parent.window.returnValue='1'; window.close()</script>");

                #region 记录日志
                var ml = new MESAuditLog();
                ml.ContainerName = txtDispContainerName.Text; ml.ContainerID = txtContainerID.Text;
                ml.ParentID = strID; ml.ParentName = parentName;
                ml.CreateEmployeeID = userInfo["EmployeeID"];
                ml.BusinessName = businessName; ml.OperationType = 0;
                ml.Description = "完工确认:" + txtSpecName.Text + ",完工确认成功";
                common.SaveMESAuditLog(ml);
                #endregion
            }
            else
            {
                Dictionary<string, object> paraUpdate = new Dictionary<string, object>();

               DataTable dtUpdate = new DataTable();
                dtUpdate.Columns.Add("id");
                dtUpdate.Rows.Add();
                dtUpdate.Rows[dtUpdate.Rows.Count - 1]["ID"] = strID + "㊣String";
               DataSet ds1 = new DataSet();
                ds1.Tables.Add(dtUpdate);
                ds1.Tables[ds1.Tables.Count - 1].TableName = "ContainerSpecFinishInfo" + "㊣ID";
                paraUpdate.Add("dsData", ds1);
                string strMessage1 = string.Empty;
                result = bll.SaveDataToDatabaseNew(paraUpdate, out strMessage1);
                result = false;
            }
            ShowStatusMessage(strMessage, result);
        }
        catch (Exception Ex)
        {
            ShowStatusMessage(Ex.Message, false);
        }
    }

    Boolean MoveContainer(Dictionary<string, string> paraNew,ref string strMessage) {
        return bll.RunMoveStd(paraNew, ref strMessage); 
    }
}